<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 *
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 *
 * @package      FeatherCMS
 * @subpackage   Contact
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class ContactController extends Controller
{
	public $_templates = 'contact';
	
	function index()
	{
		if ($this->sendEmail())
		{
			$this->message(_('Your message has been sent!'),
				_("Thank you very much for your email, we appreciate it."));
			exit;
		}
		$this->pageTitle = _('Contact us');
	}
	
	function member($member_id)
	{
		if (!empty($member_id))
		{
			$Member = $this->load->model('Member');
			$Member->process = Q_PROCESS_LITE;
			$check = $Member->read('allow_contact', $member_id, -1);
			
			if (empty($check))
				$this->flash(_('There is no such member.'), getReferer());
			
			if (!$check['allow_contact'] and !$this->acl->inGroup(Config::admins))
				$this->flash(s_('Error: %s refuses to be contacted by email.', $member_id), getReferer());
			
			$this->set('member_id', $member_id);
			$this->set('allow_contact', $check['allow_contact']);
		}
		
		if ($this->sendEmail($member_id))
		{
			$this->message(_('Your message has been sent!'),
				s_("%s should receive your message shortly.", $member_id));
			exit;
		}
		
		$this->pageTitle = s_('Send %s an email', $member_id);
		$this->render('index');
	}
	
	protected function sendEmail($member_id=null)
	{
		if (isPost() and !empty($this->data))
		{
			$Member = $this->load->model('Member');
			
			// identified? let's get sender's name and email :)
			if ($this->acl->identified)
			{
				$this->data['Contact']['name']  = $this->acl->id;
				$this->data['Contact']['email'] = $Member->field('email', $this->acl->id);
			}
			
			// is form ok?
			if ($this->Contact->validates())
			{
				$this->load->components('swift');
				
				// recipients
				if (isset($this->data['Contact']['copy']))
					$this->swift->addRecipient($this->data['Contact']['email'], $this->data['Contact']['name'], 'Cc');
				
				// recipient is website's contact or a member?
				if (empty($member_id))
					$this->swift->addRecipient(Config::website_email, Config::website_name);
				else
					$this->swift->addRecipient($Member->field('email', $member_id, -1), $member_id);
				
				// message
				$subject = empty($this->data['Contact']['subject']) ? _('No subject') : $this->data['Contact']['subject'];
				$mail_from = array($this->data['Contact']['email'], $this->data['Contact']['name']);
				
				// sends
				$this->swift->send($subject, &$mail_from);
				
				return true;
			}
		}
		return false;
	}
}
?>